package Study.Work;

public class Exam01 {
    //给定一个非空字符串和一个包含非空单词列表的字典，
    //编写一个函数来确定字符串是否可以被空格拆分为一个或多个字典中的单词。

    public static void main(String[] args) {
        String string = "cars";
        String[] wordDict = {"car" ,"ca", "rs"};
        System.out.println(workBreak2(string, wordDict)); // 输出: true
    }

    private static boolean wordBreak(String str, String[] strings) {
        //字符串为空或者字符串数组为空返货false
        if (strings.length == 0 || str.isEmpty()) {
            return false;
        }
        //将字符串中的空格替换为空字符
        str = str.replace(" ","");
        //for循环字符串，让字符串数组中第一个字符串找到字符串中的位置
        for (int i = 0; i < strings.length; i++) {
            String index = strings[i];
            //在字符串中找到字符串数组中的字符串
            if (str.contains(index)) {
                str = str.substring(index.length());
            }else{
                return false;
            }
        }
        if (!str.isEmpty()) {
            return true;
        }
        return true;
    }
    public static boolean workBreak2(String str, String[] strings) {
        char[] chars = str.toCharArray();
        int count = 0;
        for (int i = 0; i < strings.length; i++) {
            for (int j = 0; j < str.length(); j++) {
                String newstr = "";
                if (strings[count].indexOf(chars[i]) >= 0) {
                    newstr += chars[i];
            }else {
                    return false;
                }
                if (strings[count].equals(newstr)){
                    count ++;
                }
            }
        }
        return true;
    }

    public static boolean workBreak3(String s ,String[] wordDict){
        boolean[] arr = new boolean[s.length()];
        int index = 0;
        for (int i = 0; i < s.length(); i++) {
            String str = s.substring(index, i + 1);
            for (int j = 0; j < wordDict.length; j++) {
                if (wordDict[j].equals(str)) {
                    arr[i] = true;
                    index = i + 1;
                    break;
                }
            }
        }
        return arr[s.length() - 1];
    }
}
